<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/6 0006
 * Time: 下午 1:17
 */

namespace App\Http\Controllers;

use App\Http\Models\OrderModel;
use Illuminate\Http\Request;
use Validator;
use Session;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\AdvModel;
use App\Http\Models\ArticleModel;
use App\Http\Models\ExpressModel;
use App\Http\Models\PayModel;
use App\Http\Models\UserModel;
use App\Http\Models\CategoryModel;
use App\Http\Models\CustomModel;
use App\Http\Models\TimeModel;
use App\Http\Models\ExpressorderModel;
use App\Http\Models\RoomModel;
use App\Http\Models\AppointmentModel;
use App\Http\Models\Membership;

use DB;

class ApiController extends Controller
{


    //获取openid
    public function getOpenid(Request $request)
    {

        $code['code'] = $request->input('code');
        $code['nikename'] = $request->input('nikename');
        is_empty_array_data($code);
        $pay = PayModel::first();
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . trim($pay->app_id) . '&secret=' . trim($pay->app_secect) . '&js_code=' . $code['code'] . '&grant_type=authorization_code';
        $res = doCurl($url);
        //dd( $res);
        if (!empty($res['openid'])) {
            $this->add_user($res['openid'], $code['nikename']);
            $user_info= UserModel::where('openid',$res['openid'])->first();
            if($user_info->mobile){
               $user_status = 1;
            }else{
               $user_status = 0;
            }
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $res['openid'],'user_status'=>$user_status]);
        } else {
            return response()->json(['status' => 500, 'message' => '获取openid失败,请检测参数']);
        }

    }

    //增加用户
    public function add_user($openid, $name)
    {
        $user_info = UserModel::where('openid', $openid)->first();
        $data = [
            'openid' => $openid,
            'create_time' => time(),
            'nikename' => $name
        ];
        if (!$user_info) {
            UserModel::create($data);
        }
    }

    //注册用户信息
    public function upload_userinfo(Request $request)
    {
        $data = [
            'name' => $request->input('name'),
            'carded' => $request->input('carded'),
            'nikename' => $request->input('nikename'),
            'school' => $request->input('school'),
            'college' => $request->input('college'),
            'student_num' => $request->input('student_num'),
            'dormitory' => $request->input('dormitory'),
            'role' => $request->input('role'),
            'mobile' => $request->input('mobile'),
            'openid' => $request->input('openid'),
        ];
        is_empty_array_data($data);
        $user_info = UserModel::where('openid', $data['openid'])->update($data);
        if ($user_info) {
            return response()->json(['status' => 200, 'message' => '修改成功']);
        } else {
            return response()->json(['status' => 500, 'message' => '修改失败']);
        }
    }
    //修改用户信息
    public function edit_userinfo(Request $request)
    {
        $data = [
            'nikename' => $request->input('nikename'),
            'mobile' => $request->input('mobile'),
            'openid' => $request->input('openid'),
        ];
        is_empty_array_data($data);
        $user_info = UserModel::where('openid', $data['openid'])->update($data);
        if ($user_info) {
            return response()->json(['status' => 200, 'message' => '修改成功']);
        } else {
            return response()->json(['status' => 500, 'message' => '修改失败']);
        }
    }

    //获取所有的学校
    public function get_school(Request $request)
    {
        $data = CategoryModel::where('parent_id', 0)->select('id', 'name')->get();
        return response()->json(['status' => 200, 'message' => $data]);
    }

    //获取该学校下的学院
    public function get_college(Request $request)
    {
        $id = $request->input('id');
        $data['id'] = $request->input('id');
        is_empty_array_data($data);
        $data = CategoryModel::where('parent_id', $id)->select('id', 'name')->get();
        return response()->json(['status' => 200, 'message' => $data]);
    }

    //获取物流信息
    public function get_express()
    {
        $data = ExpressModel::select('id', 'name')->get()->toArray();
        //$data=array_column($data, 'name');
        return response()->json(['status' => 200, 'message' => $data]);

    }

    //获取工作时间
    public function work_time()
    {
        $data = TimeModel::get();
        return response()->json(['status' => 200, 'message' => $data]);
    }

    //获取物件的价格
    public function custom()
    {
        $data = CustomModel::get();
        return response()->json(['status' => 200, 'message' => $data]);
    }

    //获取用户的信息
    public function get_user_info(Request $request)
    {
        $data['openid'] = $request->input('openid');
        is_empty_array_data($data);
        $data = UserModel::where('openid', $request->input('openid'))->first();
        return response()->json(['status' => 200, 'message' => $data]);

    }

    //预约下单
    public function add_appointment(Request $request)
    {
        $data = array(
            'appointment_time' => $request->input('appointment_time'),
            'mobile' => $request->input('mobile'),
            'openid' => $request->input('openid'),
            'status' => $request->input('status'),
            'create_time'=>time(),
            'out_trade_no'=>md5(uniqid() . microtime())
        );
        is_empty_array_data($data);
        AppointmentModel::create($data);
        return response()->json(['status' => 200, 'message' => '预约成功']);
    }

    //增加下单时间
    public function add_express_order(Request $request)
    {
       /* $data = array(
            'out_trade_no'=>$request->input('out_trade_no'),
            'express' => $request->input('express'),
            'openid' => $request->input('openid'),
            'express_sn' => $request->input('express_sn'),
            'send_name' => $request->input('send_name'),
            'send_address' => $request->input('send_address'),
            'send_mobile' => $request->input('send_mobile'),
            'send_carded' => $request->input('send_carded'),
            'receiving_name' => $request->input('receiving_name'),
            'note' => $request->input('note'),
            'receiving_address' => $request->input('receiving_address'),
            'receiving_mobile' => $request->input('receiving_mobile'),
            'price' => $request->input('price'),
        );*/

        $data=$request->only('out_trade_no','express','openid','express_sn','send_name','send_address','send_mobile','send_carded','receiving_name','note', 'receiving_address','receiving_mobile', 'price');
        $data['create_time']=time();
        is_empty_array_data($data);
        $user=UserModel::where('openid', $data['openid'])->first();
        $data['role']= $user->role;
        ExpressorderModel::create($data);
        AppointmentModel::where(['openid'=>$request->input('openid'),'out_trade_no'=>$request->input('out_trade_no')])->update(['status'=>1]);
        return response()->json(['status' => 200, 'message' => '提交成功']);
    }

    //获取文章的信息
    public function get_article(Request $request)
    {
        $data = array(
            'id' => $request->input('id'),
        );
        is_empty_array_data($data);
        $data = ArticleModel::where('id', $request->input('id'))->first();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }
    }

    //获取该学校的宿舍楼
    public function get_room(Request $request)
    {
        $data = array(
            'school_id' => $request->input('school_id'),
        );
        is_empty_array_data($data);
        $data = RoomModel::where('school_id', $request->input('school_id'))->get();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }
    }

    //获取商家的logo
    public function get_logo(Request $request)
    {
        $data = PayModel::first();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data->logo]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }
    }

    //获取会员价格
    public function get_member_price(Request $request)
    {
        $data = PayModel::first();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' =>['price_min'=>$data->price_min,'price_max'=>$data->price_max]]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }

    }

    //取件下单支付
    public function order_pay(Request $request)
    {
        is_empty_array_data(['price'=>$request->input('price_id')]);
        $custom=CustomModel::find($request->input('price_id'));

        $data = [
            'express' => $request->input('express'),
            'express_id' => $request->input('express_id'),
            'openid' => $request->input('openid'),
            'express_sn' => $request->input('express_sn'),
            'take_number' => $request->input('take_number'),
            'price' =>$custom->content,
            'create_time'=>time()
        ];
        is_empty_array_data($data,['express_sn']);
        $user=UserModel::where('openid', $data['openid'])->first();
        $data['out_trade_no'] =md5(uniqid() . microtime());
        $data['role']= $user->role;
        $order_info= OrderModel::create($data);
        $order_id=$order_info->getQueueableId();
        //$order_id=58;
       // exit('添加成功');
        $order_info = OrderModel::find($order_id);
        $result= $this->getPaySign($order_info,'qujian');
        // dd($result);
        if($result['status']==200){
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $result]);
        }else{
            return response()->json(['status' => 500, 'message' => '请检测支付参数', 'data' => $result]);
        }

    }

    //获取支付需要的参数
    public function getPaySign($order_info,$type)
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        $notify_url = 'http://'.$_SERVER['HTTP_HOST'].'/api/payok';
        $pay_data= PayModel::find(1);
        $data = [
            //'appid' => 'wxf0d27e41678c566c',
            'appid'            => $pay_data->app_id,
            'body'             => '快递消费',
            //'mch_id'         => '1484855592',
            'mch_id'           => $pay_data->med_id,
            'nonce_str'        => md5(date('YmdHis') . time() . rand(1000, 9999)),
            'notify_url'       => $notify_url,
            'openid'           => $order_info->openid,
            'out_trade_no'     => $order_info->out_trade_no,
            'spbill_create_ip' => $ip,
            'total_fee'        => ($order_info->price)*100,
            'attach'            => $type,
            'trade_type'       => 'JSAPI'
        ];

        //形成sign
        $string = $this->getSign($data).'key='.$pay_data->med_secect;
        $stringTemp = MD5($string);
        $sign = strtoupper($stringTemp);
        //准备请求prepay接口
        $data['sign'] = $sign;
        $str_xml = "<xml>";
        foreach ($data as $key => $val) {
            $str_xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        }
        $str_xml .= "</xml>";
        $prepay_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        //请求接口并且解析xml
        $result = $this->xmlDecode($this->httpCurl($prepay_url,$str_xml));
       // dd($result);
        if ($result['return_code'] !== 'SUCCESS' || $result['result_code'] !== 'SUCCESS') {
           // return response()->json(['status'=>500,'msg'=>$result]);
            $result['status']=500;
            return  $result;
        }

        $params = [
            'appId'     => $data['appid'],
            'nonceStr'  => $data['nonce_str'],
            'package'   => 'prepay_id='.$result['prepay_id'],
            'signType'  => 'MD5',
            'timeStamp' => (string)time()
        ];
        //拼接前端需要参数
        $stringxml = $this->getSign($params).'key='.$pay_data->med_secect;
        $stringxml = MD5($stringxml);
        $sign2 = strtoupper($stringxml);
        $pay_result['paySign']   = $sign2;
        $pay_result['timeStamp'] = $params['timeStamp'];
        $pay_result['nonceStr']  = $params['nonceStr'];
        $pay_result['package']   = $params['package'];
        $pay_result['signType']  = 'MD5';
        $pay_result['status']  = 200;
        return  $pay_result;
       // return response()->json(['status'=>200,'msg'=>$pay_result]);
    }

    //获取开通会员需要的支付需要的参数
   /* public function getuserPaySign($order_info)
    {
        $ip = $_SERVER["REMOTE_ADDR"];
        $notify_url = 'http://'.$_SERVER['HTTP_HOST'].'/api/payok';
        $pay_data= PayModel::find(1);
        $data = [
            //'appid' => 'wxf0d27e41678c566c',
            'appid'            => $pay_data->app_id,
            'body'             => '快递消费',
            //'mch_id'         => '1484855592',
            'mch_id'           => $pay_data->med_id,
            'nonce_str'        => md5(date('YmdHis') . time() . rand(1000, 9999)),
            'notify_url'       => $notify_url,
            'openid'           => $order_info->openid,
            'out_trade_no'     => $order_info->out_trade_no,
            'spbill_create_ip' => $ip,
            'total_fee'        => ($order_info->price)*100,
            'trade_type'       => 'JSAPI'
        ];

        //形成sign
        $string = $this->getSign($data).'key='.$pay_data->med_secect;
        $stringTemp = MD5($string);
        $sign = strtoupper($stringTemp);
        //准备请求prepay接口
        $data['sign'] = $sign;
        $str_xml = "<xml>";
        foreach ($data as $key => $val) {
            $str_xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        }
        $str_xml .= "</xml>";
        $prepay_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        //请求接口并且解析xml
        $result = $this->xmlDecode($this->httpCurl($prepay_url,$str_xml));

        if ($result['return_code'] !== 'SUCCESS' || $result['result_code'] !== 'SUCCESS') {
            return response()->json(['status'=>500,'msg'=>$result]);
        }
        $params = [
            'appId'     => $data['appid'],
            'nonceStr'  => $data['nonce_str'],
            'package'   => 'prepay_id='.$result['prepay_id'],
            'signType'  => 'MD5',
            'timeStamp' => (string)time()
        ];
        //拼接前端需要参数
        $stringxml = $this->getSign($params).'key='.$pay_data->med_secect;
        $stringxml = MD5($stringxml);
        $sign2 = strtoupper($stringxml);
        $pay_result['paySign']   = $sign2;
        $pay_result['timeStamp'] = $params['timeStamp'];
        $pay_result['nonceStr']  = $params['nonceStr'];
        $pay_result['package']   = $params['package'];
        $pay_result['signType']  = 'MD5';
        return $pay_result ;
        //return response()->json(['status'=>200,'msg'=>$pay_result]);
    }*/
    protected function getSign($arr)
    {
        ksort($arr);
        $string = '';
        foreach ($arr as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $string .= $k . "=" . $v . "&";
            }
        }
        return $string;
    }
    protected function xmlDecode($xml)
    {
        $message = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        return $message;
    }
    protected function httpCurl($url,$data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: text'
            )
        );
        $data = curl_exec($ch);
        curl_close($ch);
        return ($data);
    }

    public function  payok(){
        error_reporting(0);
        define('IN_MOBILE', true);
        libxml_disable_entity_loader(true);
        $xml='<?xml version="1.0" encoding="utf-8"?>';
        $xml .= $GLOBALS['HTTP_RAW_POST_DATA'];
        $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $arrayinfo = xmlToArray($obj);
        if(($arrayinfo['result_code'] = 'SUCCESS' || $arrayinfo['return_code'] = 'SUCCESS'))
        {
            $out_trade_no= $arrayinfo['out_trade_no'] ; //商户订单号
            $transaction_id =$arrayinfo['transaction_id']; //微信订单支付订单号
            $attach=$arrayinfo['attach'];                 //区分是开通会员下单还是寄件下单
            $result=OrderModel::where('out_trade_no' , $out_trade_no)->find();
            if($result['status']!=1){
                $data=array(
                    'status'=>1,
                    'transaction_id'=>$transaction_id
                );
                $res=OrderModel::where('out_trade_no' , $out_trade_no)->update($data);
                if($res){
                    return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                }else{
                    return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>';
                }
            }else{
                return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            }

        }else{
            return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>';
        }

    }
    //开通会员回调封装
    public function open_membership_notify($array){
        $data=array(
            'status'=>1,
            'transaction_id'=>$array['transaction_id'],
            'create_time'=>time()
        );
        $user_data=[
            'is_member'=>1,
            'member_start_time'=>time(),
            'member_stop_time'=>strtotime("+1 months", strtotime(date("Y-m-d H:i:s", time()))),
        ];
        $user=DB::table('user')
            ->where(['openid'=>$array['openid']])
            ->first();
        if($user->member_start_time > time()){
            $user_data['member_stop_time'] =strtotime("+1 months", strtotime(date("Y-m-d H:i:s", $user->member_start_time)));
        }
        $bool=DB::transaction(function () use($array,$data, $user_data) {
            DB::table('membership')
                ->where(['out_trade_no'=>$array['out_trade_no']])
                ->update(['votes' => 1]);
            DB::table('user')
                ->where(['openid'=>$array['openid']])
                ->update( $user_data);
        });
        if($bool){
          echo true ;
        }else{
          echo flase ;
        }



    }





    //获取用户的取件订单
    public function get_user_order_qujian(Request $request)
    {
        $data=['openid'=>$request->input('openid') ];
        is_empty_array_data($data);
        $data = OrderModel::select('order.*', 'user.name', 'user.nikename', 'user.mobile')
            ->join('user', 'order.openid', '=', 'user.openid')
            ->where('order.openid',$request->input('openid') )
            ->get();
     /*   $data = OrderModel::select('order.*', 'user.name', 'user.nikename', 'user.mobile')
            ->join('user', 'order.openid', '=', 'user.openid')
            ->where('order.openid')
            ->get();*/
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }

    }

    //用户开通会员
    public function user_open_membership(Request $request)
    {
        $data=[
            'openid'=>$request->input('openid'),
            'price'=>$request->input('price'),
            'create_time'=>time()
        ];
        is_empty_array_data($data);
        $pay_data = PayModel::first();
        if((int)$data['price']==(int)$pay_data->price_min){
            $data['type'] = 0;
        }elseif( (int)$data['price']==(int)$pay_data->price_max){
            $data['type'] = 1  ;
        }else{
            return response()->json(['status' => 500, 'message' => '价格参数异常']);
        }
        $data['out_trade_no']=md5(uniqid() . microtime());
        $order_info = Membership::create($data);
        $order_id=$order_info->getQueueableId();
        if($order_id){
            $order_info = Membership::find($order_id);
            $result= $this->getPaySign($order_info,'membership');
           // dd($result);
            if($result['status']==200){
                return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $result]);
            }else{
                return response()->json(['status' => 500, 'message' => '请检测支付参数', 'data' => $result]);
            }
        }
    }

    //获取用户的预约寄件订单
    public function get_user_appointment_order(Request $request)
    {
        $data=['openid'=>$request->input('openid') ];
        is_empty_array_data($data);
        $data = AppointmentModel::select('appointment.*','user.nikename','user.mobile','user.name')
            ->join('user','appointment.openid','=','user.openid')
            ->where('appointment.openid',$request->input('openid'))
            ->get();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }

    }


    //获取用户的寄件信息
    public function  get_user_express_order(Request $request){
        $data=['openid'=>$request->input('openid') ];
        is_empty_array_data($data);
        $data = ExpressorderModel::where('openid',$request->input('openid'))->get();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }
    }

    //获取当前订单是否已经提交过了
    public function get_one_express_order(Request $request)
    {
        $data=['out_trade_no'=>$request->input('out_trade_no'),
            'openid'=>$request->input('openid')
            ];
        is_empty_array_data($data);
        $data = ExpressorderModel::where($data)->first();
        if (!empty($data)) {
            return response()->json(['status' => 200, 'message' => '获取成功', 'data' => $data]);
        } else {
            return response()->json(['status' => 500, 'message' => '暂无该数据']);
        }
    }

    public function test(Request $request)
    {

        echo   date("Y-m-d H:i:s", strtotime("+1 months", strtotime(date("Y-m-d H:i:s", time()))));


    }



}